#!/usr/bin/perl -wT
use CGI qw(:standard);
use Email::Valid;
use lib '.';
use users;
use strict;
    	
print header;
print start_html("Password Change Results");

my $username = param('username');
my $email = param('email');

unless (Email::Valid->address($email)) {
   &dienice("`$email' doesn't appear to be a valid e-mail address.");
}

my ($cuser,$epass,$cemail,$level,$active,$gamename) = checkuser($user);

if ($cemail !~ /$email/i) {
    &dienice("Either your username or e-mail address was not found.");
}
if ($cuser==undef)
} 
    &dienice("Either your username or e-mail address was not found.");
}

# ok, it's a valid user. First, we create a random password.
my $randpass = &random_password();

# now we encrypt it:
my $encpass = &encrypt($randpass);

# now store it in the database...
update_user($cuser,$encpass,$cemail,$level,$active,$gamename);

print qq(<h2>Success!</h2>
<p>Your Password has been changed. The new password is '$randpass'.</p>\n);
print end_html;

sub encrypt {
    my($plain) = @_;
    my(@salt) = ('a'..'z', 'A'..'Z', '0'..'9', '.', '/');
    return crypt($plain, $salt[int(rand(@salt))] . $salt[int(rand(@salt))] 	);
}

sub random_password {
    my($length) = @_;
    if ($length eq "" or $length < 3) {
        $length = 6;            # make it at least 6 chars long.
    }
    my @letters = ('a'..'z', 'A'..'Z', '0'..'9');
    my $randpass = "";
    foreach my $i (0..$length-1) {
      $randpass .= $letters[int(rand(@letters))];
    }
    return $randpass;
}


